<template>
  <el-dialog
    :title="title"
    :model-value="visible"
    :draggable="true"
    width="80%"
    :before-close="handleClose"
    append-to-body
    class="largeScreen-dialog analyzeAndWarn"
  >
    <el-tabs v-model="activeName" class="tabs-box" @tab-click="handleClick">
      <el-tab-pane label="隐患分析" name="first">
        <el-row :gutter="10" type="flex" align="middle" justify="space-between">
          <el-col :span="10">
            <h3>隐患类型</h3>
            <div :style="styleObject">
              <barCharts :options="hiddenDangerStatus" :width="styleObject.width" :height="styleObject.height"></barCharts>
            </div>
          </el-col>
          <el-col :span="10">
            <h3>隐患整改状态</h3>
            <el-row :gutter="10" type="flex" align="middle" justify="center">
              <el-col :span="6">
                <el-radio-group v-model="typeStatus">
                  <el-radio-button value="2">已整改</el-radio-button>
                  <el-radio-button value="3">未整改</el-radio-button>
                </el-radio-group>
              </el-col>
            </el-row>
            <div :style="styleObject">
              <barCharts :options="rectificationHiddenDangers" :width="styleObject.width" :height="styleObject.height"></barCharts>
            </div>
          </el-col>
        </el-row>
        <el-row :gutter="10" type="flex" align="middle" justify="space-between">
          <el-col :span="10">
            <h3>隐患趋势</h3>
            <div :style="styleObject">
              <barCharts :options="hiddenDangerAnalysis" :width="styleObject.width" :height="styleObject.height"></barCharts>
            </div>
          </el-col>
          <el-col :span="10">
            <h3>隐患分布</h3>
            <div :style="styleObject">
              <barCharts :options="distributionHiddenDangers" :width="styleObject.width" :height="styleObject.height"></barCharts>
            </div>
          </el-col>
        </el-row>
        <el-row :gutter="10" type="flex" align="middle" justify="space-between">
          <el-col :span="24">
            <h3>隐患管理列表</h3>
            <div class="table-box">
              <el-table
                :data="tableData"
                max-height="500"
                style="width: 100%; font-size: 16px"
                v-loading="loading"
                :row-style="{ height: '50px' }"
                :cell-style="{ padding: '0px' }"
                element-loading-background="rgba(0,0,0,0.2)"
                ref="scrollTable"
              >
                <el-table-column
                  :prop="item.prop"
                  :label="item.label"
                  :min-width="item.width"
                  :align="item.align"
                  v-for="(item, index) in column"
                  :key="index"
                  show-overflow-tooltip
                >
                  <template #default="scope">
                    <el-carousel :interval="3000" height="100px" style="width: 100%" v-if="item.prop === 'url' && scope.row.url">
                      <el-carousel-item v-for="item in scope.row.url" :key="item.id">
                        <el-image preview-teleported style="width: 100%; height: 100%" :src="scope.row.url" :preview-src-list="[scope.row.url]" />
                      </el-carousel-item>
                    </el-carousel>
                    <el-button
                      style="color: white"
                      link
                      v-else-if="item.prop === 'surroundingEnvironment' && scope.row.longitudeg && scope.row.latitude"
                      @click="open(scope.row)"
                    >
                      查看
                    </el-button>
                    <dict-tag v-else-if="item.prop === 'type'" :options="hazard_category" :value="scope.row.type" />
                    <dict-tag v-else-if="item.prop === 'grade'" :options="pitfall_grade" :value="scope.row.type" />
                    <span v-else>{{ scope.row[item.prop] }}</span>
                  </template>
                </el-table-column>
              </el-table>
              <pagination v-show="total > 0" :total="total" v-model:page="params.pageNo" v-model:limit="params.pageSize" @pagination="getList" />
            </div>
          </el-col>
        </el-row>
      </el-tab-pane>
      <el-tab-pane label="风险分析" name="second">
        <el-row :gutter="10" type="flex" align="middle" justify="space-between">
          <el-col :span="10">
            <h3>燃气管网风险等级</h3>
            <div :style="styleObject">
              <barCharts :options="riskStatus" v-if="activeName == 'second'" :width="styleObject.width" :height="styleObject.height"></barCharts>
            </div>
          </el-col>
          <el-col :span="10">
            <h3>风险指数统计</h3>
            <div :style="styleObject">
              <pie-echarts
                v-if="alarmStatisticsData.echartsData.length > 0 && activeName == 'second'"
                :title="'告警类型统计'"
                :echarts-data="alarmStatisticsData.echartsData"
              />
            </div>
          </el-col>
        </el-row>
        <el-row :gutter="10" type="flex" align="middle" justify="space-between" v-if="activeName == 'second'">
          <el-col :span="10">
            <el-row :gutter="10" type="flex" align="middle" justify="space-between">
              <el-col :span="12">
                <h3>风险指数趋势图</h3>
              </el-col>
              <el-col :span="12">
                <el-date-picker
                  v-model="trendDateRange"
                  type="daterange"
                  range-separator="至"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  value-format="YYYY-MM-DD"
                  size="small"
                  :shortcuts="dateShortcuts"
                  class="trend-date-picker"
                />
              </el-col>
            </el-row>
            <div :style="styleObject">
              <Chart
                :xAxis="line.xAxis"
                :yAxis="line.yAxis"
                :series="line.series"
                :legend="line.legend"
                :tooltip="line.tooltip"
                :grid="line.grid"
                :width="styleObject.width"
                :height="styleObject.height"
              ></Chart>
            </div>
          </el-col>
          <el-col :span="10">
            <h3>行政区划风险指数排名</h3>
            <div :style="styleObject">
              <barCharts :options="rank" :width="styleObject.width" :height="styleObject.height"></barCharts>
            </div>
          </el-col>
        </el-row>
      </el-tab-pane>
    </el-tabs>
    <monitorVideo v-model="pointInfo" ref="monitorVideoRef" />
  </el-dialog>
</template>

<script lang="ts" setup>
import { ref, watch } from 'vue';
import {
  listPitfall,
  category,
  categoryAnalysis,
  getStatisticByCompany,
  getRightData,
  lineTrendIndex,
  getAlarmByCounty
} from '@/api/earlyWarning/index.js';
import { pipelineNetworkPieData } from '@/api/pipelineNetworkRisk/index.js';
import monitorVideo from './monitorVideo/index.vue';
import pieEcharts from '@/components/ECharts/alertOverviewPie/index.vue';
import Chart from '@/components/ECharts/Chart/index.vue';
import barCharts from './echarts/barCharts.vue';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

// Chart configurations
const riskStatus = ref({
  tooltip: {
    trigger: 'axis',
    axisPointer: {
      type: 'shadow'
    }
  },
  grid: {
    left: '3%',
    right: '4%',
    bottom: '3%',
    containLabel: true
  },
  xAxis: {
    type: 'category',
    data: [],
    axisLine: {
      lineStyle: {
        color: '#00ffff'
      }
    },
    axisLabel: {
      color: '#fff'
    }
  },
  yAxis: {
    type: 'value',
    axisLine: {
      show: true,
      lineStyle: {
        color: '#00ffff'
      }
    },
    axisLabel: {
      color: '#fff'
    },
    splitLine: {
      lineStyle: {
        color: 'rgba(0, 255, 255, 0.2)'
      }
    }
  },
  series: [
    {
      data: [],
      type: 'bar',
      showBackground: true,
      barWidth: '15%',
      backgroundStyle: {
        color: 'rgba(180, 180, 180, 0.2)'
      },
      itemStyle: {
        color: '#00a2ff'
      }
    }
  ]
});

const hiddenDangerAnalysis = ref({
  tooltip: {
    trigger: 'axis'
  },
  legend: {
    data: [],
    textStyle: {
      color: '#fff'
    }
  },
  grid: {
    left: '3%',
    right: '4%',
    bottom: '3%',
    containLabel: true
  },
  xAxis: {
    type: 'category',
    boundaryGap: false,
    data: [],
    axisLine: {
      lineStyle: {
        color: '#00ffff'
      }
    },
    axisLabel: {
      color: '#fff'
    }
  },
  yAxis: {
    type: 'value',
    axisLine: {
      show: true,
      lineStyle: {
        color: '#00ffff'
      }
    },
    axisLabel: {
      color: '#fff'
    },
    splitLine: {
      lineStyle: {
        color: 'rgba(0, 255, 255, 0.2)'
      }
    }
  },
  series: [
    {
      data: [],
      type: 'bar',
      barWidth: '15%',
      itemStyle: {
        color: '#00a2ff'
      }
    }
  ]
});

const hiddenDangerStatus = ref({
  tooltip: {
    trigger: 'axis',
    axisPointer: {
      type: 'shadow'
    }
  },
  grid: {
    left: '3%',
    right: '4%',
    bottom: '3%',
    containLabel: true
  },
  xAxis: {
    type: 'category',
    data: [],
    axisLine: {
      lineStyle: {
        color: '#00ffff'
      }
    },
    axisLabel: {
      color: '#fff',
      rotate: 30
    }
  },
  yAxis: {
    type: 'value',
    axisLine: {
      show: true,
      lineStyle: {
        color: '#00ffff'
      }
    },
    axisLabel: {
      color: '#fff'
    },
    splitLine: {
      lineStyle: {
        color: 'rgba(0, 255, 255, 0.2)'
      }
    }
  },
  series: [
    {
      data: [],
      type: 'bar',
      showBackground: true,
      barWidth: '15%',
      backgroundStyle: {
        color: 'rgba(180, 180, 180, 0.2)'
      },
      itemStyle: {
        color: '#00a2ff'
      }
    }
  ]
});

const rectificationHiddenDangers = ref({
  tooltip: {
    trigger: 'axis',
    axisPointer: {
      type: 'shadow'
    }
  },
  grid: {
    left: '3%',
    right: '4%',
    bottom: '3%',
    containLabel: true
  },
  xAxis: {
    type: 'category',
    data: [],
    axisLine: {
      lineStyle: {
        color: '#00ffff'
      }
    },
    axisLabel: {
      color: '#fff',
      rotate: 30
    }
  },
  yAxis: {
    type: 'value',
    axisLine: {
      show: true,
      lineStyle: {
        color: '#00ffff'
      }
    },
    axisLabel: {
      color: '#fff'
    },
    splitLine: {
      lineStyle: {
        color: 'rgba(0, 255, 255, 0.2)'
      }
    }
  },
  series: [
    {
      data: [],
      type: 'bar',
      showBackground: true,
      barWidth: '15%',
      backgroundStyle: {
        color: 'rgba(180, 180, 180, 0.2)'
      },
      itemStyle: {
        color: '#00a2ff'
      }
    }
  ]
});

const distributionHiddenDangers = ref({
  tooltip: {
    trigger: 'axis',
    axisPointer: {
      type: 'shadow'
    }
  },
  grid: {
    left: '3%',
    right: '4%',
    bottom: '3%',
    containLabel: true
  },
  xAxis: {
    type: 'category',
    data: [],
    axisLine: {
      lineStyle: {
        color: '#00ffff'
      }
    },
    axisLabel: {
      color: '#fff',
      rotate: 30
    }
  },
  yAxis: {
    type: 'value',
    axisLine: {
      show: true,
      lineStyle: {
        color: '#00ffff'
      }
    },
    axisLabel: {
      color: '#fff'
    },
    splitLine: {
      lineStyle: {
        color: 'rgba(0, 255, 255, 0.2)'
      }
    }
  },
  series: [
    {
      data: [],
      type: 'bar',
      showBackground: true,
      barWidth: '15%',
      backgroundStyle: {
        color: 'rgba(180, 180, 180, 0.2)'
      },
      itemStyle: {
        color: '#00a2ff'
      }
    }
  ]
});

const line = ref({
  tooltip: {
    trigger: 'axis'
  },
  legend: {
    data: [],
    textStyle: {
      color: '#fff'
    }
  },
  grid: {
    left: '3%',
    right: '4%',
    bottom: '3%',
    containLabel: true
  },
  xAxis: [
    {
      type: 'category',
      boundaryGap: false,
      data: [],
      axisLine: {
        lineStyle: {
          color: '#00ffff'
        }
      },
      axisLabel: {
        color: '#fff'
      }
    }
  ],
  yAxis: [
    {
      type: 'value',
      axisLine: {
        show: true,
        lineStyle: {
          color: '#00ffff'
        }
      },
      axisLabel: {
        color: '#fff'
      },
      splitLine: {
        lineStyle: {
          color: 'rgba(0, 255, 255, 0.2)'
        }
      }
    }
  ],
  series: [
    {
      data: [],
      type: 'bar',
      showBackground: true,
      barWidth: '15%',
      backgroundStyle: {
        color: 'rgba(180, 180, 180, 0.2)'
      },
      itemStyle: {
        color: '#00a2ff'
      }
    }
  ]
});

const rank = ref({
  tooltip: {
    trigger: 'axis',
    axisPointer: {
      type: 'shadow'
    }
  },
  grid: {
    left: '3%',
    right: '4%',
    bottom: '3%',
    containLabel: true
  },
  xAxis: {
    type: 'value',
    axisLine: {
      lineStyle: {
        color: '#00ffff'
      }
    },
    axisLabel: {
      color: '#fff'
    },
    splitLine: {
      lineStyle: {
        color: 'rgba(0, 255, 255, 0.2)'
      }
    }
  },
  yAxis: {
    type: 'category',
    data: [],
    axisLine: {
      lineStyle: {
        color: '#00ffff'
      }
    },
    axisLabel: {
      color: '#fff'
    }
  },
  series: [
    {
      data: [],
      type: 'bar',
      showBackground: true,
      barWidth: '15%',
      backgroundStyle: {
        color: 'rgba(180, 180, 180, 0.2)'
      },
      itemStyle: {
        color: '#00a2ff'
      }
    }
  ]
});

const column = ref([
  { prop: 'name', label: '隐患名称', width: '120', align: 'center' },
  { prop: 'type', label: '隐患类型', width: '120', align: 'center' },
  { prop: 'grade', label: '隐患等级', width: '120', align: 'center' },
  { prop: 'location', label: '隐患位置', width: '120', align: 'center' },
  { prop: 'discoveryTime', label: '发现时间', width: '120', align: 'center' },
  { prop: 'url', label: '隐患图片', width: '120', align: 'center' },
  { prop: 'rectificationStatus', label: '整改状态', width: '120', align: 'center' },
  { prop: 'surroundingEnvironment', label: '周边环境', width: '120', align: 'center' }
]);

const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  title: {
    type: String,
    default: '预警分析一张图'
  }
});

const emit = defineEmits(['update:visible', 'openViewer']);

const tableData = ref([]);
const total = ref(0);
const params = ref({
  pageNo: 1,
  pageSize: 10
});
const loading = ref(false);
const styleObject = ref({
  width: '621px',
  height: '300px'
});
const typeStatus = ref('2');
const activeName = ref('first');
const alarmStatisticsData = ref({
  echartsData: []
});
const pointInfo = ref({});
const scrollTable = ref(null);
const trendDateRange = ref([]);

const dateShortcuts = [
  {
    text: '本日',
    value: () => {
      const today = new Date();
      return [today, today];
    }
  },
  {
    text: '本周',
    value: () => {
      const end = new Date();
      const start = new Date();
      const day = start.getDay();
      const diff = start.getDate() - day + (day === 0 ? -6 : 1);
      start.setDate(diff);
      return [start, end];
    }
  },
  {
    text: '本月',
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setDate(1);
      return [start, end];
    }
  },
  {
    text: '本年',
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setMonth(0);
      start.setDate(1);
      return [start, end];
    }
  }
];

const { hazard_category, pitfall_grade } = toRefs<any>(proxy?.useDict('hazard_category', 'pitfall_grade'));
const monitorVideoRef = ref(null);
const getList = async () => {
  loading.value = true;
  try {
    const [listRes, pieRes, categoryRes, analysisRes, rectificationRes, companyRes, alarmRes, trendRes, countyRes] = await Promise.all([
      listPitfall(params.value),
      pipelineNetworkPieData(),
      category({ searchType: 'YEAR' }),
      categoryAnalysis(),
      categoryAnalysis({ type: typeStatus.value }),
      getStatisticByCompany(),
      getRightData({ type: 'alarmStatistics' }),
      lineTrendIndex({ searchType: 'YEAR' }),
      getAlarmByCounty()
    ]);

    // Process table data
    tableData.value = listRes.rows || [];
    total.value = listRes.total || 0;

    // Process risk status data
    riskStatus.value.xAxis.data = pieRes.data?.map((item) => item.name) || [];
    riskStatus.value.series[0].data = pieRes.data?.map((item) => item.value) || [];

    // Process hidden danger analysis
    if (categoryRes.code === 200) {
      hiddenDangerAnalysis.value.legend.data = categoryRes.data.legend?.data || [];
      hiddenDangerAnalysis.value.xAxis.data = categoryRes.data.xaxisList?.[0]?.data || [];
      hiddenDangerAnalysis.value.series = categoryRes.data.seriesList || [];
    }

    // Process hidden danger status
    hiddenDangerStatus.value.xAxis.data = analysisRes.data?.analysis?.map((item) => item.name) || [];
    hiddenDangerStatus.value.series[0].data = analysisRes.data?.analysis?.map((item) => item.count) || [];

    // Process rectification status
    rectificationHiddenDangers.value.xAxis.data = rectificationRes.data?.analysis?.map((item) => item.name) || [];
    rectificationHiddenDangers.value.series[0].data = rectificationRes.data?.analysis?.map((item) => item.count) || [];

    // Process distribution data
    distributionHiddenDangers.value.xAxis.data = companyRes.data?.map((item) => item.name) || [];
    distributionHiddenDangers.value.series[0].data = companyRes.data?.map((item) => item.count) || [];

    // Process alarm statistics
    alarmStatisticsData.value.echartsData = alarmRes.data?.alarmStatistics?.echartsData || [];

    // Process trend data
    line.value.legend.data = trendRes.data?.legend?.data || [];
    line.value.xAxis[0].data = trendRes.data?.xaxisList?.[0]?.data || [];
    line.value.series = trendRes.data?.seriesList || [];

    // Process county rank data
    rank.value.yAxis.data = countyRes.data?.map((item) => item.countyName) || [];
    rank.value.series[0].data = countyRes.data?.map((item) => item.num) || [];
  } catch (error) {
    console.error('Error fetching data:', error);
  } finally {
    loading.value = false;
  }
};

const getTrendData = async () => {
  try {
    const trendParams: any = {};

    if (trendDateRange.value && trendDateRange.value.length === 2) {
      trendParams.startTime = trendDateRange.value[0];
      trendParams.endTime = trendDateRange.value[1];
      trendParams.searchType = 'CUSTOM';
    } else {
      trendParams.searchType = 'YEAR';
    }

    const trendRes = await lineTrendIndex(trendParams);

    // Process trend data
    line.value.legend.data = trendRes.data?.legend?.data || [];
    line.value.xAxis[0].data = trendRes.data?.xaxisList?.[0]?.data || [];
    line.value.series = trendRes.data?.seriesList || [];
  } catch (error) {
    console.error('Error fetching trend data:', error);
  }
};

const handleClose = () => {
  params.value = {
    pageNo: 1,
    pageSize: 10
  };
  tableData.value = [];
  total.value = 0;
  trendDateRange.value = [];
  emit('update:visible', false);
};

const open = (row) => {
  pointInfo.value = row;
  monitorVideoRef.value.open();
};

const handleClick = (tab) => {
  if (tab.props.name === 'second') {
    getList();
  }
};

watch(typeStatus, () => {
  getList();
});

watch(trendDateRange, () => {
  if (activeName.value === 'second') {
    getTrendData();
  }
});

watch(
  () => props.visible,
  (val) => {
    if (val) {
      getList();
    }
  },
  { immediate: true }
);
</script>

<style scoped lang="scss">
h3 {
  color: #00ffff;
}

.trend-date-picker {
  width: 100%;

  :deep(.el-input__wrapper) {
    background-color: rgba(0, 78, 112, 0.6);
    border: 1px solid #00ffff;
    box-shadow: none;

    &:hover {
      border-color: #00ffff;
      box-shadow: 0 0 8px rgba(0, 255, 255, 0.4);
    }
  }

  :deep(.el-input__inner) {
    color: #fff;
    font-size: 13px;
  }

  :deep(.el-range-separator) {
    color: #00ffff;
  }

  :deep(.el-range-input) {
    color: #fff;
    background-color: transparent;

    &::placeholder {
      color: rgba(255, 255, 255, 0.5);
    }
  }

  :deep(.el-input__prefix) {
    color: #00ffff;
  }

  :deep(.el-input__suffix) {
    color: #00ffff;
  }
}

.table-box {
  :deep(.el-table) {
    --el-table-border-color: #004e70;
    --el-table-header-bg-color: transparent;
    --el-table-row-hover-bg-color: transparent;
    --el-table-text-color: #fff;
    --el-table-header-text-color: #00ffff;
    --el-table-border: none;

    background-color: transparent;

    /* 全局样式中 */
    .el-table__header-wrapper th {
      background: linear-gradient(180deg, #004db9 0%, #01347b 48%, #014cb5 100%);
      color: #0ff;
    }

    .el-table__body {
      tr {
        background-color: #083577;
        color: #fff;

        td {
          border-bottom: 1px solid #0a73a0;
          cursor: pointer;
        }
      }
    }

    .el-table__empty-block {
      background-color: #003556;

      .el-table__empty-text {
        color: #00ffff;
        font-size: 24px;
      }
    }

    /* Scrollbar styles */
    .el-table__body-wrapper {
      &::-webkit-scrollbar {
        width: 0.5rem;
        height: 0.5rem;
        background-color: #3f8af3;
        border-radius: 0.375rem;
      }

      &::-webkit-scrollbar-thumb {
        background-color: #1c4682;
        border-radius: 0.375rem;
      }
    }
  }

  .pagination-container {
    background: #083577;
    padding: 10px 16px;
    text-align: right;
    margin: 0;
  }

  .pagination-container.hidden {
    display: none;
  }

  :deep(.el-pagination__total) {
    color: #fff;
  }

  :deep(.el-pagination__jump) {
    color: #fff;
  }
}
</style>

<style lang="scss">
.tabs-box {
  color: #ffffff;
  width: 100%;

  .chart-box {
    width: 100%;
  }

  .el-tabs__item {
    font-family: PangMenZhengDao;
    color: #409eff;
  }

  .el-tabs__item.is-active {
    color: #00ffff !important;
  }

  .el-tabs__active-bar {
    background-color: #00ffff !important;
  }

  .el-tabs__nav-wrap::after {
    position: static !important;
  }
}

.analyzeAndWarn {
  .el-dialog__body {
    background-color: #083577;
  }
}

.el-picker-panel {
  background-color: #083577;
  border: 1px solid #00ffff;

  .el-picker-panel__body {
    color: #fff;
  }

  .el-picker-panel__sidebar {
    background-color: rgba(0, 78, 112, 0.6);
    border-right: 1px solid #00ffff;
    width: 120px;
  }

  .el-picker-panel__shortcut {
    color: #fff;
    font-size: 13px;
    padding: 8px 12px;

    &:hover {
      color: #00ffff;
      background-color: rgba(0, 255, 255, 0.1);
    }
  }

  .el-date-range-picker__content {
    background-color: #083577;
  }

  .el-date-table td {
    color: #fff;

    &.available:hover {
      color: #00ffff;
    }

    &.today span {
      color: #00ffff;
      font-weight: bold;
    }

    &.in-range div,
    &.in-range div:hover {
      background-color: rgba(0, 162, 255, 0.2);
    }

    &.start-date span,
    &.end-date span {
      background-color: #00a2ff;
      color: #fff;
    }
  }

  .el-date-table th {
    color: #00ffff;
  }

  .el-month-table td {
    color: #fff;

    &.today .cell {
      color: #00ffff;
      font-weight: bold;
    }

    &.start-date .cell,
    &.end-date .cell {
      background-color: #00a2ff;
      color: #fff;
    }
  }

  .el-year-table td {
    color: #fff;

    &.today .cell {
      color: #00ffff;
      font-weight: bold;
    }

    &.start-date .cell,
    &.end-date .cell {
      background-color: #00a2ff;
      color: #fff;
    }
  }

  .el-date-picker__header-label {
    color: #fff;

    &:hover {
      color: #00ffff;
    }
  }

  .el-picker-panel__icon-btn {
    color: #fff;

    &:hover {
      color: #00ffff;
    }
  }

  .el-date-range-picker__header {
    .el-picker-panel__icon-btn,
    div {
      color: #fff;
    }
  }
}
</style>
